package com.okwanshiwu.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.okwanshiwu.payment.aliUtil.AliProperties;
import com.okwanshiwu.payment.wxUtil.ParseXMLUtils;
import com.okwanshiwu.service.interfaces.Pay;
import com.okwanshiwu.util.PageData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.TreeMap;

/**
 * 支付控制类
 *
 * @author
 * @create 2017-08-02 17:11
 **/
@RestController
@RequestMapping(value = "/pay")
public class PayController extends BaseController{

	@Autowired
	private Pay pay;

	/**
	 * 微信支付完成回调接口
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "wxPayment")
	@ResponseBody
	public String wxPayment(HttpServletRequest req){
		String signFailMsg = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>";
		String failMsg = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![接收支付失败]></return_msg></xml>";
		String successMsg = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[ok]]></return_msg></xml>";
		InputStream is = null;
		BufferedReader br = null;
		StringBuffer buf = new StringBuffer();
		try {
			is = req.getInputStream();
			br = new BufferedReader(new InputStreamReader(is));
			String temp = null;
			while((temp = br.readLine())!= null){
				buf.append(temp);
			}
			if(buf.length() < 1){
				return signFailMsg;
			}
			logger.info("---通知了结果："+buf.toString()+"--");
		} catch (IOException e) {
			e.printStackTrace();
			return failMsg;
		}
		Map<String,Object> payResult = ParseXMLUtils.jdomParseXml(buf.toString());
		Map<Object,Object> nsm = new TreeMap<Object,Object>();
		for(Map.Entry e:payResult.entrySet()){
			nsm.put(e.getKey(),e.getValue());
		}
		return pay.handleOrder(nsm,"wxPay")?successMsg:failMsg;
	}

	/**
	 * 支付宝被动回调方法
	 * @return
	 */
	@RequestMapping(value = "aliPayment")
	public String aliPayment(){
		PageData pd = this.getPageData(); //将异步通知中收到的待验证所有参数都存放到map中
		try {
			boolean signVerified = AlipaySignature.rsaCheckV1(pd, AliProperties.ALI_PUBLIC_KEY, "utf-8"); //调用SDK验证签名
			if(signVerified){
				// TODO 验签成功后
				//按照支付结果异步通知中的描述，对支付结果中的业务内容进行1\2\3\4二次校验，校验成功后在response中返回success，校验失败返回failure
				return pay.handleOrder(pd,"aliPay")?"success":"fail";
			}else{
				// TODO 验签失败则记录异常日志，并在response中返回failure.
				logger.info("aliPay签名验证没有通过");
			}
		} catch (AlipayApiException e) {
			e.printStackTrace();
			logger.error("aliPay被动回调验证签名出错，可能是有冒充支付宝的恶意请求");
		}
		return "fail";
	}


}
